import React, { useEffect, useState } from 'react';
import { message, Card, Space } from 'antd';
import StudentSearch from './components/StudentSearch';
import StudentTable from './components/StudentTable';
import StudentToolbar from './components/StudentToolbar';
import StudentModal from './components/StudentModal';
import { 
  Student, 
  getStudentList,
  createStudent, 
  updateStudent, 
  removeStudent,
} from '../../service/student';

const StudentList: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [tableColumns, setTableColumns] = useState<any[]>([]);
  const [visibleColumns, setVisibleColumns] = useState<string[]>([]);
  const [studentList, setStudentList] = useState<Student[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchParams, setSearchParams] = useState<{
    username?: string;
    name?: string;
    sex?: string;
    email?: string;
    classId?: string;
    status?: number;
    startTime?: number;
    endTime?: number;
  }>({});
  const [modalVisible, setModalVisible] = useState(false);
  const [editingStudent, setEditingStudent] = useState<Student | undefined>(undefined);

  const fetchStudentList = async () => {
    try {
      setLoading(true);
      console.log('Search Params:', searchParams);
      const res = await getStudentList({
        page: currentPage,
        pagesize: pageSize,
        ...searchParams
      });
      console.log('API Response:', res.data);
      if (res.data.code === 0) {
      setStudentList(res.data.data.list);
      setTotal(res.data.data.total);
    } else {
      message.error(res.data.msg || '获取学生列表失败');
    }
    } catch (error) {
      console.error('获取学生列表出错:', error);
      message.error('获取学生列表出错');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStudentList();
  }, [currentPage, pageSize, searchParams]);

  const handleSearch = (values: any) => {
    console.log('Search Values:', values);
    const searchParams = { ...values };
    // 如果有 name（性别）参数，将其转换为 sex
    if (searchParams.name) {
      searchParams.sex = searchParams.name;
      delete searchParams.name;
    }
    setSearchParams(searchParams);
    setCurrentPage(1);
  };

  const handleReset = () => {
    setSearchParams({});
    setCurrentPage(1);
  };

  const handleAdd = () => {
    setEditingStudent(undefined);
    setModalVisible(true);
  };

  const handleEdit = (record: Student) => {
    setEditingStudent(record);
    setModalVisible(true);
  };

  const handleModalOk = async (values: any) => {
    try {
      console.log('提交的表单数据:', values);
      
      const formData = {
        username: values.username,
        password: values.password,
        name: values.name,
        sex: values.sex || undefined,
        age: values.age || undefined,
        email: values.email || undefined,
        classId: values.className,
        idCard: values.idCard || undefined,
        status: values.status ?? 1
      };
      
      console.log('处理后的提交数据:', formData);
      
      if (editingStudent) {
        // 编辑学生
        const res = await updateStudent({
          id: editingStudent._id,
          ...formData,
          // 明确指定 classId，避免可能的班级操作问题
          classId: values.className
        });
        console.log('更新学生响应:', res);
        
        if (res.data.code === 0) {
          message.success('更新学生成功');
          setModalVisible(false);
          fetchStudentList();
        } else {
          console.error('更新学生失败:', res);
          message.error(res.data.msg || '更新学生失败');
        }
      } else {
        // 添加学生
        const res = await createStudent({
          ...formData,
          classId: values.className
        });
        console.log('添加学生响应:', res);
        
        if (res.data.code === 0) {
          message.success('添加学生成功');
          setModalVisible(false);
          fetchStudentList();
        } else {
          console.error('添加学生失败:', res);
          message.error(res.data.msg || '添加学生失败');
        }
      }
    } catch (error: any) {
      console.error('操作失败，详细错误:', error);
      
      if (error.response) {
        message.error(`操作失败: ${error.response.status} - ${error.response.data.msg || '未知错误'}`);
      } else if (error.request) {
        // 请求已发出，但没有收到响应
        message.error('操作失败：服务器无响应');
      } else {
        // 在设置请求时发生了错误
        message.error('操作失败：请求发送错误');
      }
    }
  };

  const handleDelete = async (id: string) => {
    try {
      console.log('准备删除学生，ID:', id);
      const token = localStorage.getItem('token');
      console.log('当前token:', token);
      
      if (!token) {
        message.error('请先登录');
        window.location.href = '/login';
        return;
      }

      const res = await removeStudent({ id });
      console.log('删除响应:', res.data);
      
      if (res.data?.code === 0) {
        message.success('删除成功');
        fetchStudentList();
      } else {
        console.error('删除失败，响应数据:', res.data);
        message.error(res.data?.msg || '删除失败');
      }
    } catch (error: any) {
      console.error('删除失败:', error);
      
      if (error.response?.status === 401) {
        message.error('登录已过期，请重新登录');
        window.location.href = '/login';
      } else if (error.response) {
        console.error('服务器响应:', error.response.data);
        message.error(error.response.data?.msg || '删除失败');
      } else if (error.request) {
        message.error('服务器无响应');
      } else {
        message.error('请求发送错误');
      }
    }
  };

  const handlePageChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
  };

  return (
    <Card>
      <Space direction="vertical" size="middle" style={{ width: '100%' }}>
        <StudentSearch onSearch={handleSearch} onReset={handleReset} />
        
        <StudentToolbar 
          onAdd={handleAdd} 
          onRefresh={fetchStudentList}
          columns={tableColumns}
          onColumnsChange={(newColumns) => {
            setVisibleColumns(
              newColumns
                .filter(col => col.visible !== false)
                .map(col => col.dataIndex || col.key)
            );
          }}
        />

        <StudentTable
          loading={loading}
          studentList={studentList}
          total={total}
          currentPage={currentPage}
          pageSize={pageSize}
          onEdit={handleEdit}
          onDelete={handleDelete}
          onPageChange={handlePageChange}
          visibleColumns={visibleColumns}
          onColumnsChange={setTableColumns}
        />
      </Space>

      <StudentModal
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={handleModalOk}
        editingStudent={editingStudent}
        title={editingStudent ? '编辑学生' : '添加学生'}
      />
    </Card>
  );
};

export default StudentList;